package com.keppardo.dyndns;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;

public class MailSender {

	private String to;
	private String from;
	private String text;
	private String pwdMail = "mangioleghiande";
	private String usrMail = "ipchanged@gmail.com";
	private String smtpServer = "smtp.gmail.com";
	private String porta = "587";
	private Authenticator auth;

	public MailSender(String to, String from, final String usrMail,
			final String pwdMail) {
		this.from = from;
		this.to = to;
		this.auth = new Authenticator() {

			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// TODO Auto-generated method stub
				return new PasswordAuthentication(usrMail, pwdMail);
			}

		};
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public void sendMail(String ipAddress) throws MessagingException {
		Properties props = System.getProperties();
		// -- Attaching to default Session, or we could start a new one --
		props.put("mail.smtp.host", smtpServer);
		props.put("mail.smtp.port", porta);
		props.put("mail.smtp.auth", "true");
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.starttls.enable", "true");

		Session session = Session.getDefaultInstance(props, auth);
		// -- Create a new message --
		MimeMessage msg = new MimeMessage(session);
		// -- Set the FROM and TO fields --
		msg.setFrom(new InternetAddress(from));
		msg.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(
				to, false));
		// -- We could include CC recipients too --
		// if (cc != null)
		// msg.setRecipients(Message.RecipientType.CC
		// ,InternetAddress.parse(cc, false));
		// -- Set the subject and body text --
		msg.setSubject("Cambio indirizzo ip");
		msg.setText("Nuovo ip: " + ipAddress);
		// -- Set some other header information --
		msg.setHeader("X-Mailer", "LOTONtechEmail");
		msg.setSentDate(new Date());
		// -- Send the message --
		Transport.send(msg);
		System.out.println("Message sent OK.");
	}

	public String getSmtpServer() {
		return smtpServer;
	}

	public void setSmtpServer(String smtpServer) {
		this.smtpServer = smtpServer;
	}

	public void setSmtpPort(String smtpPort) {
		this.porta = smtpPort;
	}

}
